package top.hkyzf.study.leetcode.linkedlist;

import org.junit.Test;

/**
 * @author 朱峰
 * @date 2022-1-28 10:23
 */
public class 反转链表_206 {
    public ListNode reverseList2(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode prev = null;
        ListNode current = head;
        while (current != null) {
            ListNode next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        return prev;
    }

    public ListNode reverseList1(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList1(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    @Test
    public void testReverseList () {
        ListNode node4 = new ListNode(5);
        ListNode node3 = new ListNode(4, node4);
        ListNode node2 = new ListNode(3, node3);
        ListNode node1 = new ListNode(2, node2);
        ListNode head1 = new ListNode(1, node1);
        ListNode head = reverseList(head1);
        while (head != null) {
            System.out.println(head);
            head = head.next;
        }
    }
}
